import 'dart:convert';

import 'package:baseProjectFlutter/mode/base/base_data.dart';
import 'package:dio/dio.dart';

import '../../generated/json/base/json_convert_content.dart';
import '../../utils/http/http_manager.dart';
import '../../utils/http/http_ui_handle.dart';

class HttpUtils {
  /// 发送Get请求
  static Future<T> get<T>({
    HttpUiHandle? handle,
    String url = "",
    String? path,
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) async {
    return request<T>(
      url: url,
      path: path,
      data: data,
      queryParameters: queryParameters,
      options: HttpManager.checkOptions('GET', options),
      cancelToken: cancelToken,
      onSendProgress: onSendProgress,
      onReceiveProgress: onReceiveProgress,
    );
  }

  /// 发送请求
  static Future<T> request<T>({
    HttpUiHandle? handle,
    String url = "",
    String? path,
    dynamic data,
    Map<String, dynamic>? queryParameters,
    Options? options,
    CancelToken? cancelToken,
    ProgressCallback? onSendProgress,
    ProgressCallback? onReceiveProgress,
  }) async {
    handle?.start();
    var result;
    Response res;
    try {
      res = await HttpManager.dio.request(
          (url.isEmpty) ? HttpManager.createUrl(path: path) : url,
          options: HttpManager.checkOptions('POST', options),
          data: data,
          queryParameters: queryParameters,
          cancelToken: cancelToken,
          onSendProgress: onSendProgress,
          onReceiveProgress: onReceiveProgress);
      //解析成mode
      result = _parseData<T>(jsonDecode(res.data));
      HttpManager.handleResult(result, handle: handle);
      handle?.success(result);
    } catch (e) {
      handle?.error(e);
      //这里只有抛出错误才能阻止调用者继续执行
      rethrow;
    } finally {
      handle?.completed();
    }
    //如果hander没有设置 直接返回结果
    return result;
  }

  /// 解析结果
  static T _parseData<T>(Map<String, dynamic> json) {
    var result;
    if (T == HttpResponse) {
      result = HttpResponse().fromJson(json);
    } else if (T == HttpResult) {
      result = HttpResult().fromJson(json);
    } else if (T == HttpPageResult) {
      result = HttpPageResult().fromJson(json);
    } else {
      //无法识别的类型使用 JsonConvert
      result = JsonConvert.fromJsonAsT<T>(json);
    }
    return result;
  }
}
